<?php
/**
 * BaseModelOptionTrait.php
 * 文件描述 数据库基础操作：增删改查...
 * Created on 2020/8/31 11:53
 * Created by 刘小龙 595929049@qq.com
 * status 当前完成度：20%
 */

namespace app\common\traits;


trait BaseModelOptionTrait
{
    //获取详情
    public function getRow($filter ,$field = [])
    {
        $result  = $this->where($filter);
        if(!empty($field)) $result = $result->field($field);
        return $result->find();
    }
    //获取列表
    public function listRow($filter ,$page_config = [] ,$order = null ,$field = [])
    {
        if(empty($page_config)) $page_config = ['page' => 1 ,'page_count' =>20];
        $result = $this->where($filter);
        if(!empty($order)) $result = $result->order($order);
        if(!empty($field)) $result = $result->field($field);
        return $result->page($page_config['page'] ,$page_config['page_count'])->select();
    }
    //创建
    public function createRow($data)
    {
        return self::create($data);
    }
    //批量创建
    public function createRows($datas)
    {
        return $this->saveAll($datas);
    }
    //更新
    public function updateRow($filter ,$data)
    {
        $data['update_time'] = time();
        $result = $this->where($filter)->update($data);
        return !empty($result);
    }
    //删除
    public function deleteRow($filter)
    {
        $result =  $this->where($filter)->delete( );
        return !empty($result);
    }
    //统计
    public function getCount($filter) {
        return  $this->where($filter)->count();
    }

    //获取某个值的总数
    public function getValuesSum($filter ,$key) {
        $result = $this->where($filter)->sum($key);
        return $result;
    }
    //某个值增加
    public function incData($filter ,$data) {
        $result = $this->where($filter);
        foreach ($data as $key => $value) {
            $result->inc($key ,$value);
        }
        $result = $result->update();
        return !empty($result);
    }

    //某个值减少
    public function decData($filter ,$data) {
        $result = $this->where($filter);
        foreach ($data as $key => $value) {
            $result->dec($key ,$value);
        }
        $result = $result->update();
        return !empty($result);
    }
}
